$(function () {
    $.getScript("/api/sso/myinfo?cb=cb");
})

function cb(info) {

    if (info.state == 1) {
        showLoginUi()
    } else {
        $.get("/api/server/myAccount?" + new Date().getTime(), showAwardInfo);
        showUserInfo(info);
    }
}

function showAwardInfo(data) {

    var myAccount = data.Account;
    if (!myAccount) {
        return;
    }

    var orders = data.Order;
    if (!orders.length) {
        return;
    }
    //
    if (myAccount.types == 2) {
        $("#calcAward").show()
    }
//
    var awardCount = 0, layer, layerAward = 0, amountAward = 0, luckyAward = 0, managementAward = 0, charmAward = 0;
    var aa = data.AmountAward;
    var aaHtml = [];
    orders.forEach(function (value, index, array) {

        managementAward += value.AwardManagement
        luckyAward += value.AwardLucky
        amountAward += value.AwardAmount
        layerAward += value.AwardLayer
        charmAward += value.AwardCharm
        //
        var b = aa[value.Id];
        if (b && b.id) {
            aaHtml.push('<h3 class="moreinfo">');
            aaHtml.push('<span class="tit">单号:</span><span class="con" id="danhao">' + value.Id + '</span>');
            aaHtml.push('<span class="tit">业绩:</span><span class="con" id="yeji">0</span>');
            aaHtml.push('<span class="tit">左区余:</span><span class="con" id="leftarea">' + b.leftPrice + '</span>');
            aaHtml.push('<span class="tit">右区余:</span><span class="con" id="rightarea">' + b.rightPrice + '</span>');
            aaHtml.push('</h3>');
        }
    });

    if (aaHtml.length) {
        $('article.award').find('.moreinfo').remove();
        $('article.award').append(aaHtml.join(''));
    }

    awardCount = (layerAward + amountAward + luckyAward + managementAward + charmAward)


    var options = {
        useEasing: true,
        useGrouping: true,
        separator: ',',
        decimal: '.',
        prefix: '',
        suffix: '.0'
    };

    new CountUp("awardCount", 0, awardCount, 0, 3, options).start();
    $("#orderCount").text(orders.length)

    $("#layerAward").text(layerAward)
    $("#amountAward").text(amountAward)
    $("#luckyAward").text(luckyAward)
    $("#managementAward").text(managementAward)
    $("#charmAward").text(myAccount.charmAward)


    var c = data.myRecommended, d = 0;
    if (c && c.length > 0) {
        c.forEach(function (c1, c2) {
            d += c1.Price
        })
        $('#recomin').text(c.length || 0)
        $('#orderssum').text(d || 0)
    }


    /*
     var preData = [
     {name: "层碰奖", value: layerAward},
     {name: "量碰奖", value: amountAward},
     {name: "幸运奖", value: luckyAward},
     {name: "管理奖", value: managementAward},
     {name: "魅力奖", value: charmAward},
     ];
     myawardchart(preData);
     */

    // 不启用 msg
    // connectWs()
}


// 登陆界面
function showNewOrderUI() {
    var refId = 09;
    var htm = [];
    htm.push('<div class="newOrder" >')
    htm.push('<a class="iconfont  icon-close-empty icon-close" ></a>')
    htm.push('<h2 > 报单 </h2>')
    htm.push('<form id="login">')
    htm.push('<span ><em class="iconfont icon-shouji"></em><input   type="text" placeholder="手机" name="mobile" value="" /></span>')
    htm.push('<span ><em class="iconfont icon-dengji"></em><select  placeholder="金额" name="price" >')
    htm.push('<option value="3000" selected >普通会员（3000）</option>')
    htm.push('<option value="10000" >银卡会员（10000）</option>')
    htm.push('<option value="20000" >金卡会员（20000）</option>')
    htm.push('<option value="30000" >白金会员（30000）</option>')
    htm.push('</select></span>')
    htm.push('<span ><em class="iconfont icon-shouji"></em><input   type="text" placeholder="推荐人手机" name="introducerMob"   value="" /></span>')
    htm.push('<a class="submit" >确定</a>')
    htm.push('</form>')
    htm.push('</div>')

    $('#dialog').html(htm.join('')).show();
    $('#dialog').find('.submit').click(newOrderFn)
    $('#dialog').find('.icon-close').click(closeDialog)
}
function showApprovesList() {

    var approveOkok = function (apid) {
        var url = "/api/server/approve?apid=" + apid;
        $.get(url, function (res) {
            if (res && res == 9) {
                alert("通过")
                $("#apid" + apid).remove();
            }
        })
    }

    var url = "/api/server/myapproves";
    $.get(url, function (res) {
        if (!res || res.length == 0) return;

        var htm = [];
        htm.push('<div class="myapproves" >')
        htm.push('<a class="iconfont icon-close-empty icon-close" ></a>')
        htm.push('<h2 > 我的审批 </h2>')
        htm.push('<p class="tip" > 确认对方是本人操作的！ </p>')
        htm.push('<ul>')
        res.forEach(function (a, b) {
            htm.push('<li id="apid' + a.id + '" ><em>' + a.proposerAccountMob + ' 的 二级密码重置</em><a onclick="approveOkok(' + a.id + ')" >通过</a></li>')
        })

        htm.push('</ul>')
        htm.push('</div>')


        $('#dialog').html(htm.join('')).show();
        $('#dialog').find('.icon-close').click(closeDialog)

    });

}

function showGrantNewOrderUI() {
    var htm = [];
    htm.push('<div class="grantNewOrder" >')
    htm.push('<a class="iconfont icon-close-empty icon-close" ></a>')
    htm.push('<h2 > 允许报单 </h2>')
    htm.push('<form id="param">')
    htm.push('<span ><em class="iconfont icon-icon"></em><input   type="text" placeholder="手机" name="mob" value="18620131415" /></span>')
    htm.push('<a class="submit" >确定</a>')
    htm.push('</form>')
    htm.push('</div>')

    var grantNewOrderFn = function () {
        var mob = $("#param [name='mob']").val()
        var url = "/api/server/grantNewOrder?mob=" + mob;
        $.get(url, function (res) {
            if (!res) {
                alert("失败！")
                return;
            }
            alert(res.msg)
            $("#dialog").hide().html("");
        })

    }

    $('#dialog').html(htm.join('')).show();
    $('#dialog').find('.submit').click(grantNewOrderFn)
    $('#dialog').find('.icon-close').click(closeDialog)
}

var MSGOBJ = {
    CalcAwarIsOk: function (msg) {
        var fn = function () {
            var btn = $("#calcAward");
            btn.html("计算奖金");
            btn.removeClass('off').addClass('on')
            btn.click(showCalcAwar)
        }
        if (msg) setTimeout(fn, 3000)
    },

    Send: function (msg) {
        sock.send(nsg);
    }
}

function connectWs() {
    sock = new WebSocket(wsuri);
    sock.onopen = function () {
        console.log("connected to " + wsuri);
    }
    sock.onclose = function (e) {
        console.log("connection closed (" + e.code + ")");
    }
    sock.onmessage = function (e) {
        var obj = JSON.parse(e.data);
        (typeof(MSGOBJ[obj.method]) == "function") ? MSGOBJ[obj.method](e) : console.log(obj);
    }
};


function showCalcAwar() {
    var url = '/api/server/calcAward'
    var result = function (res) {
        var btn = $("#calcAward");
        btn.html("计算中...");
        btn.removeClass('on').addClass('off')
        btn.removeAttr('onclick')
    }

    $.ajax({
        type: "get",
        url: url,
        success: result
    });
}


function newOrderFn() {
    var url = '/api/server/newOrder'
    var data = $("#login").serializeObject()
    if (!(/^1(3|4|5|7|8)\d{9}$/.test(data.mobile))) {
        alert("手机号码有误，请重填");
        return;
    }
    if (!(/^1(3|4|5|7|8)\d{9}$/.test(data.introducerMob))) {
        alert("手机号码有误，请重填");
        return;
    }


    var newOrderResult = function (res) {
        if (res) {
            alert(res.msg)
            $("#dialog").html("").hide()
        }
    }

    $.ajax({
        type: "POST",
        url: url,
        data: JSON.stringify(data),
        contentType: 'application/json',
        success: newOrderResult
    });


}


// 奖金报表
function myawardchart(data) {

    var myChart = echarts.init(document.getElementById('myawardchart'));

    var app = {}, option = {};

    app.title = '双轨制奖金收入比例：';

    option = {
        tooltip: {
            trigger: 'item',
            formatter: "{a} <br/>{b}: {c} ({d}%)"
        },
        series: [

            {
                name: '奖金来源：',
                type: 'pie',
                radius: ['15%', '30%'],
                label: {
                    normal: {
                        formatter: '{a|{a}}{abg|}\n{hr|}\n  {b|{b}：}{c}  {per|{d}%}  ',
                        backgroundColor: '#fff',
                        borderColor: '#dfdfdf',
                        borderWidth: 1,
                        borderRadius: 4,
                        // shadowBlur:3,
                        // shadowOffsetX: 2,
                        // shadowOffsetY: 2,
                        // shadowColor: '#999',
                        // padding: [0, 7],
                        rich: {
                            a: {
                                color: '#999',
                                lineHeight: 22,
                                align: 'center'
                            },
                            // abg: {
                            //     backgroundColor: '#333',
                            //     width: '100%',
                            //     align: 'right',
                            //     height: 22,
                            //     borderRadius: [4, 4, 0, 0]
                            // },
                            hr: {
                                borderColor: '#aaa',
                                width: '100%',
                                borderWidth: 0.5,
                                height: 0
                            },
                            b: {
                                fontSize: 9,
                                lineHeight: 12
                            },
                            per: {
                                color: '#eee',
                                backgroundColor: '#f1833b',
                                padding: [2, 6],
                                borderRadius: 4
                            }
                        }
                    }
                },
                data: data
            }
        ]
    };
    ;
    if (option && typeof option === "object") {
        myChart.setOption(option, true);
    }
}



